import "dart:io";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/api.dart";
import "package:ct_pa_majordomo/pages/commonApi.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/state/common.dart";
import "package:ct_pa_majordomo/utils/common.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:dio/dio.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:image_picker/image_picker.dart";
import "package:provider/provider.dart";

class Cohabitant extends StatefulWidget {
  final List cohabitantList;
  const Cohabitant({super.key, required this.cohabitantList});

  @override
  State<StatefulWidget> createState() => _CohabitantState();
  
}

class _CohabitantState extends State<Cohabitant> {
  late ImagePicker _imagePicker;
  XFile? _imageFile;
  List _list = [];

  bool validateIdCard(String? value) {
    if (value == null || value.isEmpty) {
      return false;
    }
    return true;
  }

  Widget _renderFace(int index) {
    if (_list[index]["imageFile"] != null) {
      return Image.file(
        File(_list[index]["imageFile"]!.path),
        width: 150,
        height: 150,
      );
    } else if (_list[index]["picUrl"] != null && _list[index]["picUrl"].isNotEmpty) {
      return Image.network(
        _list[index]["picUrl"],
        width: 150,
        height: 150,
      );
    }
    return Container(
      width: 150,
      height: 150,
      decoration: const BoxDecoration(
        color: ThemeVars.colorBackground,
      ),
      child: const Icon(Icons.add, size: 50,),
    );
  }

  // 选择图片
  Future<void> _pickImage(int index) async {
    final pickedImage = await _imagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _list[index]["imageFile"] = pickedImage;
    });
  }

  // 人脸上传
  Future<void> _uploadImage(index) async {
    if (_list[index]["imageFile"] != null) {
      FormData formData = FormData();
      formData.files.add(MapEntry("file", await MultipartFile.fromFile(_list[index]["imageFile"]!.path, filename: _list[index]["imageFile"]!.name)));
      Map res = await commonApi.upload(formData);
      setState(() {
        _list[index]["picUrl"] = res["data"]["url"];
        _list[index].remove("imageFile");
      });
      print("图片信息：$res");
    }
  }

  Widget _renderList(int index) {
    if (index == _list.length) {
      return Button(
          type: ButtonType.normal,
          radius: 0,
          onPressed: () {
            setState(() {
              Map cohabitant = {
                "name": "",
                "contacts": "",
                "idCardNumber": "",
                "mainFlag": 0,
              };
              _list.add(cohabitant);
            });
          },
          child: const Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.add, size: 20,),
              Text("添加同住人"),
            ],
          )
      );
    }
    Map item = _list[index];
    return MenuBlock(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text("同住人${index + 1}"),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                setState(() {
                  _list.removeAt(index);
                });
              },
              child: const Text("删除", style: TextStyle(color: ThemeVars.colorError, fontSize: 14),),
            )
          ],
        ),
        items: [
          MenuBlockItem(
            text: "姓名",
            showArrow: false,
            prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError),),
            suffix: TextFormField(
              textAlign: TextAlign.right,
              decoration: const InputDecoration(
                hintStyle: TextStyle(color: ThemeVars.colorTextTer, fontWeight: FontWeight.w400),
                hintText: "请输入",
                isDense: true,
              ),
              initialValue: item["name"],
              onChanged: (value) => setState(() {
                _list[index]["name"] = value;
              }),
            ),
          ),
          MenuBlockItem(
            text: "联系方式",
            showArrow: false,
            prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError),),
            suffix: TextFormField(
              textAlign: TextAlign.right,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                hintStyle: TextStyle(color: ThemeVars.colorTextTer, fontWeight: FontWeight.w400),
                hintText: "请输入手机号",
                isDense: true,
              ),
              initialValue: item["contacts"],
              onChanged: (value) => setState(() {
                _list[index]["contacts"] = value;
              }),
            ),
          ),
          // 办理入住时先隐藏人脸认证 因为人脸需要renterId，入住办理时操作不了
          // MenuBlockItem(
          //   text: "人脸",
          //   showArrow: false,
          //   tip: Column(
          //     crossAxisAlignment: CrossAxisAlignment.start,
          //     children: [
          //       _renderFace(index),
          //       const Text("人脸仅用于租客门禁开锁使用", style: TextStyle(color: ThemeVars.colorWarning, fontSize: 12),)
          //     ],
          //   ),
          //   // suffix: Icon(Icons.image_outlined),
          //   onTap: () {
          //     _pickImage(index);
          //   },
          // ),
          MenuBlockItem(
            text: "证件号",
            showArrow: false,
            tip: const Text("证件号仅用于租客办理入住登记使用", style: TextStyle(color: ThemeVars.colorWarning, fontSize: 12),),
            suffix: TextFormField(
              textAlign: TextAlign.right,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                hintStyle: TextStyle(color: ThemeVars.colorTextTer, fontWeight: FontWeight.w400),
                hintText: "请输入",
                isDense: true,
              ),
              initialValue: item["idCardNumber"],
              onSaved: (value) => setState(() {
                _list[index]["idCardNumber"] = value;
              }),
            ),
          )
        ]
    );
  }
  
  bool _validate() {
    bool pass = true;
    for (var item in _list) {
      if (item["name"].isEmpty || item["contacts"].isEmpty) {
        EasyLoading.showToast("请填写完整");
        pass = false;
      }
      if (!CommonTools.phone(item["contacts"])) {
        EasyLoading.showToast("请填写正确的手机号码");
        pass = false;
      }
    }
    return pass;
  }

  @override
  void initState() {
    _imagePicker = ImagePicker();
    setState(() {
      _list = widget.cohabitantList.isNotEmpty
          ? widget.cohabitantList
          : [{ "name": "", "contacts": "", "idCardNumber": "", "picUrl": "", "mainFlag": 0}];
    });
    print("同住人：》》》 $_list");
    super.initState();
  }


  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "同住人",
      actions: [
        TextButton(
          onPressed: () async{
            print(_list);
            if (_validate()) {
              for (int i = 0; i < _list.length; i++) {
                await _uploadImage(i);
              }
              if (context.mounted) {
                Navigator.pop(context, _list);
              }
            }
          },
          child: const Text("保存", style: TextStyle(color: Colors.white),)
        ),
      ],
      child: ListView.separated(
        itemBuilder: (BuildContext context, index) => _renderList(index),
        separatorBuilder: (BuildContext context, index) => const SizedBox(height: 12,),
        itemCount: _list.length + 1
      )
    );
  }
  
}